var express = require('express');
var router = express.Router();
let myQuery = require('../tools/db')
let {apiUrl} = require('../tools/config')


//banner 的接口
router.get('/banners',async(req,res,next)=>{
  let sql = `SELECT CONCAT('${apiUrl}',image_src) AS image_src,title FROM e_banners WHERE isshow=1;`;
  let [err,result] = await myQuery(sql);

  if(err){
    next({code:500, msg:err});
    return;
  }

  res.send({code:200, msg:'ok',result});
})

//首页列表接口
router.get('/indexlist',async(req,res,next)=>{
  let {type=1} = req.query;

  let lim = type == 1? 8 : 6;

  let sql = `SELECT cid,CONCAT('${apiUrl}','course/',image_src) AS image_src, title, price, intro, type, type_name,
  area_name, subject_name FROM e_course WHERE type=${type} LIMIT 0,${lim};`
  let [err,result] = await myQuery(sql);

  if(err){
    next({code:500, msg:err});
    return;
  }

  res.send({code:200, msg:'ok',result});
})

//搜索接口
router.get('/indexsearch',async(req,res,next)=>{
  let {keywords='',pagenum = 6,page = 1} = req.query; 
  
  let [err,[{totals}]] = await myQuery(`SELECT COUNT(*) AS totals FROM e_course WHERE title LIKE '%${keywords}%';`)
  console.log(totals);
  
  if(err){
    next({code:500, msg:err});
    return;
  }

  let allpagenum = Math.ceil(totals/pagenum);

  let startNum = (page - 1) * pagenum;


  let sql = `SELECT id, cid,CONCAT('${apiUrl}','course/',image_src) AS image_src, title, price, intro, type, type_name,
  area_name, subject_name FROM e_course WHERE title LIKE '%${keywords}%' LIMIT ${startNum},${pagenum};`

  let [err1,result] = await myQuery(sql);


  if(err1){
    next({code:500, msg:err1});
    return;
  }

  console.log(result);

  res.send({code:200, msg:'ok',totals,allpagenum,page,keywords,result});
})

module.exports = router;


